<template>
	<view class="update-info">
		<NavBar title="修改信息"/>
		<view class="form-box flex-column">
			<image :src="avatar" class="avatar" @tap="upload"/>
			<wd-input label="账号" label-width="30px" v-model="formData.username" clearable/>
			<wd-button class="btn" @tap="submit"> 提交 </wd-button>
		</view>
	</view>
</template>

<script setup>
	import { ref } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import NavBar from '@/components/NavBar.vue';
	import { uploadApi, editUserInfoApi } from '@/api'
	import { useUserStore } from '@/store'
	const formRef = ref()
	const avatar = ref('')
	const formData = ref({
		uid: '',
		avatar: '',
		username: ''
	})
	const upload = () => {
		uploadApi().then(res =>{
			const { data, status, message } = res
			if(status == '200') {
				formData.value.avatar = data.id
				avatar.value = data.url
			} else {
				uni.showToast({
					icon: 'none',
					title: message
				})
			}
		})
	}
	const submit = () => {
		const { userInfo, SETUSERINFO } = useUserStore()
		editUserInfoApi({...formData.value}).then(res => {
			uni.navigateBack()
			SETUSERINFO({
				...userInfo,
				avatar: avatar.value,
				avatar_id: formData.value.avatar,
			})
		})
	}
	onLoad(() => {
		const { userInfo } = useUserStore()
		formData.value = {
			uid: userInfo.uid,
			avatar: userInfo.avatar_id,
			username: userInfo.username
		}
		avatar.value = userInfo.avatar
	})
</script>

<style lang="scss" scoped>
	.update-info {
		padding: 20rpx 24rpx;
		padding-top: 60rpx;
		.form-box {
			gap: 50rpx;
			padding: 20rpx;
			border-radius: 20rpx;
			background-color: #fff;
			align-items: center;
			.avatar {
				width: 200rpx;
				height: 200rpx;
				border-radius: 50%;
				border: 6rpx solid #f8f8f8;
			}
			.wd-input {
				border-bottom: 1px solid #f8f8f8;
			}
			.btn {
				width: 60%;
			}
		}
	}
</style>
